package systempen.cmanager;

import java.io.File;
import java.io.StringWriter;
import java.sql.Date;
import java.util.Calendar;

import systempen.cmanager.DialogAccountBrowser.IFoundAccount;
import systempen.cmanager.DialogTypeBrowser.IFoundCostType;
import android.R.bool;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Camera;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.DateTimeKeyListener;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ConfirmInsert extends Activity {
	//ListActivity thisclass;
	//private String[] lv_arr;
	static final private int EDIT_AMOUNT = 11;
	static final private int EDIT_DESCRIPTION = 2;
	static final private int EDIT_DATE = 3;
	private static final int TAKE_PICTURE = 1;
	TextView txtCostCode;
	TextView txtCostCodeN;
	TextView txtValue;
	TextView txtWhe;
	TextView txtDescription;
	TextView txtPath;
	TextView txtAccount;
	TextView txtAccountN;
	String Operation;
	String a;
	String _account;
	public Uri imageUri;
	@Override
	public void onCreate(Bundle icicle){
		super.onCreate(icicle);
		ThemePicker.onActivityCreateSetTheme(this);
		try{
			setContentView(R.layout.confirminsert2);
			Bundle bun = getIntent().getExtras();
			txtCostCode = (TextView)findViewById(R.id.textCode);//invisible one
			txtCostCodeN = (TextView)findViewById(R.id.textCostTypeN);
			txtValue = (TextView)findViewById(R.id.textAmount);
			txtWhe = (TextView)findViewById(R.id.textDateN);
			txtDescription = (TextView)findViewById(R.id.textDescriptionN);
			txtPath = (TextView)findViewById(R.id.textTypePathN);
			txtAccount = (TextView)findViewById(R.id.textAccount);
			txtAccountN = (TextView)findViewById(R.id.textAccountN);

			txtAccountN.setText(util.getDefaultAccountName(getApplicationContext()));
			_account = util.getDefaultAccountCode(getApplicationContext());

			txtCostCode.setText(bun.getString("cost_code"));
			txtCostCodeN.setText(util.getLevelName(txtCostCode.getText().toString(), getApplicationContext()));
			txtValue.setText(bun.getString("value"));
			txtWhe.setText(bun.getString("whe"));
			txtDescription.setText(bun.getString("description"));
			txtPath.setText(bun.getString("path"));
			Operation = bun.getString("operation");
			a = bun.getString("a");

		}//od try
		catch(Exception ex) 
		{
			Toast.makeText(this,"ConfirmInsert: "+ex.getMessage(), Toast.LENGTH_LONG).show();
		}
	}
	public String getPathOfLevel(String levelID){// duplikat sa CostTypes.java trebalo mi je 4 sata za ovo, al sam izlapio... note to self: sledeci put iskopiraj, konju!
		String parent = util.parentLevelExists(levelID,getApplicationContext());
		if (parent!=""){//ako postoji parent daj ga ako ne onda to je to
			String povratni = getPathOfLevel(parent) +" > "+util.getLevelName(levelID,getApplicationContext());
			return povratni;
		}else{
			if (levelID.equals("0")){
				levelID = "Root";
			}
			return levelID;
		}
	}
	public void onOK (View view){
		SharedPreferences prefsRead = getSharedPreferences("CMANAGER", Context.MODE_PRIVATE);
		String picName = prefsRead.getString("PictureName", "");
		
		String sql="";
		String dateForInsert = "";
		ContentValues cv = new ContentValues();
		dateForInsert = util.ConvertToDbFormat(txtWhe.getText().toString(),getApplicationContext());
		cv.put("cost_code", Integer.parseInt(txtCostCode.getText().toString()));
		cv.put("value", Float.parseFloat(txtValue.getText().toString()));
		cv.put("whe", dateForInsert);
		cv.put("description", txtDescription.getText().toString());
		cv.put("account", Float.parseFloat(_account.toString()));
		cv.put("picture", picName.toString());
		if (Operation.equals("Insert")){
			//sql = "INSERT INTO log (cost_code, value, whe, description) values ("+txtCostCode.getText()+","+txtValue.getText()+", \'"+dateForInsert+"\', \'"+txtDescription.getText()+"\')"; //radi datum i bez zagrade, sta ti je server
			util.DBInsert(cv, getApplicationContext(), "log");//jebo sam mu mater sporu...
			//new InsertTask().execute(cv);
		} 
		else{
			sql = "update log set cost_code = "+txtCostCode.getText()+", value = "+txtValue.getText()+", whe = \'"+dateForInsert+"\', description = \'"+txtDescription.getText()+"\'"+" account = "+_account+" "
					+" picture = \'"+picName+"\'"
					+" where a = "+a.toString();
			util.DBUpdate(cv, getApplicationContext(), "log", "a = "+a.toString(), null);
		}
		//util.execSQL(sql,  this);
		Toast.makeText( this ,"Cost successfully processed.", Toast.LENGTH_SHORT).show();
		try{
			Intent intent = new Intent(Intent.ACTION_VIEW);
			if (view.getTag().toString().equals("1")) //Razlika Save ili Save & Add New
				intent.putExtra("CurrentTab", 1);
			else
				intent.putExtra("CurrentTab", 0);
			intent.setClassName(this, MainActivityTab.class.getName());
			this.startActivity(intent);
		}catch (Exception ex){
			util.showDialog("ehm, :"+ex.getMessage().toString(), this); 
		}
	}
	public void onCancel(View view){
		startActivity(new Intent(getApplicationContext(), MainActivityTab.class));
	}
	public void onCamera2(View v){
		try{
			//Intent intent = new Intent(Intent.ACTION_VIEW);
			//intent.setClassName(this, CameraActivity.class.getName());
			//this.startActivity(intent);
		}catch (Exception ex){
			//util.showDialog("ehm, :"+ex.getMessage().toString(), this); 
		}
	}
	public void ShowImage(String imageName){
		SharedPreferences prefs = getSharedPreferences("CMANAGER", Context.MODE_PRIVATE);
		boolean imageExists = prefs.getBoolean("PictureExists", false);
		if (imageExists){
			ImageView imageView = (ImageView) findViewById(R.id.image);
			ContentResolver cr = getContentResolver();
			Bitmap bitmap;
			try {
				String filepath = Environment.getExternalStorageDirectory()+"/CostManager/Pictures/"+imageName;

				File f = new File(filepath);
				if (f.exists()) {
					Drawable d = Drawable.createFromPath(filepath);
					BitmapFactory.Options options = new BitmapFactory.Options();
					options.inSampleSize = 4;
					Bitmap bm = BitmapFactory.decodeFile(filepath, options);
					imageView.setImageBitmap(bm); 
				}
			} catch (Exception e) {
				Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
				Log.e("Camera", e.toString());
			}
		}
	}
	public void onCamera(View view) {
		String uniqueFileName = String.format("%d.jpg", System.currentTimeMillis());
		SharedPreferences prefs = getSharedPreferences("CMANAGER", Context.MODE_PRIVATE);
		SharedPreferences.Editor ed = prefs.edit();
		ed.putString("PictureName", uniqueFileName); //picture name
		ed.commit(); 

		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		File photo = new File(Environment.getExternalStorageDirectory()+"/CostManager/Pictures/",  uniqueFileName);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
		imageUri = Uri.fromFile(photo);
		startActivityForResult(intent, TAKE_PICTURE);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case TAKE_PICTURE:
			if (resultCode == Activity.RESULT_OK) {
				try {
					SharedPreferences prefs = getSharedPreferences("CMANAGER", Context.MODE_PRIVATE);
					SharedPreferences.Editor ed = prefs.edit();
					ed.putBoolean("PictureExists", true);
					ed.commit();
					SharedPreferences prefsRead = getSharedPreferences("CMANAGER", Context.MODE_PRIVATE);
					String picName = prefsRead.getString("PictureName", "");

					ShowImage(picName);
				} catch (Exception e) {
					Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
					.show();
					Log.e("Camera", e.toString());
				}

			}
		}
	}
	@Override
	protected void onResume() {
		super.onResume();
		SharedPreferences prefs = getSharedPreferences("CMANAGER", Context.MODE_PRIVATE);
		String imageName = prefs.getString("PictureName", "");
		ShowImage(imageName);

		//dodati shared
	} 

	public void onChooseAccount(View v){
		IFoundAccount ifa = new IFoundAccount() {

			@Override
			public void onFoundAccount(String account) {
				// TODO Auto-generated method stub
				_account = account;
				txtAccountN.setText(util.getAccountName(account, getApplicationContext()));
			}
		};
		DialogAccountBrowser dab = new DialogAccountBrowser(ConfirmInsert.this, ifa);
		dab.show();
	}
	public void onImageClick(View view){
		SharedPreferences prefs = getSharedPreferences("CMANAGER", Context.MODE_PRIVATE);
		String imageName = prefs.getString("PictureName", "");
		String imagePath = Environment.getExternalStorageDirectory()+"/CostManager/Pictures/"+imageName.toString();
		File f = new File(imagePath);
		boolean b = f.exists();
		if(imageName != null && !imageName.equals("")){
			Intent intent = new Intent();
			intent.setAction(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.fromFile(f), "image/*");
			//intent.setDataAndType(Uri.parse("file://" + "/sdcard/CostManager/"+imageName.toString()), "image/*");
			startActivity(intent);
		}
	}

	public void onModify(View view){
		//Toast.makeText(this, "Implemented!", Toast.LENGTH_SHORT).show();
		final CharSequence[] items = {"Change Amount","Change Description","Change Date","Change Type","Change Account"};

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Choose option to change");
		builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
				if (items[item].equals("Change Amount")){
					showDialog(EDIT_AMOUNT);//ovaj prikazuje dialog a dialog preko globalnih parametara zna sta treba da radi, valjda
				}
				if (items[item].equals("Change Description")){
					showDialog(EDIT_DESCRIPTION);//ovaj prikazuje dialog a dialog preko globalnih parametara zna sta treba da radi, valjda		        	
				}
				if (items[item].equals("Change Date")){
					showDialog(EDIT_DATE);//ovaj prikazuje dialog a dialog preko globalnih parametara zna sta treba da radi, valjda		        	
				}
				if (items[item].equals("Change Type")){
					IFoundCostType ifo = new IFoundCostType() {

						@Override
						public void onFoundCostType(String costType) {
							txtCostCode.setText(costType);
							txtCostCodeN.setText(util.getLevelName(costType,getApplicationContext()));
							txtPath.setText(getPathOfLevel(costType));
						}
					};
					DialogTypeBrowser dt = new DialogTypeBrowser(ConfirmInsert.this, "0", ifo);
					dt.show();	
				}
				if (items[item].equals("Change Account")){
					IFoundAccount ifo = new IFoundAccount() {
						@Override
						public void onFoundAccount(String account) {
							_account = account;
							txtAccountN.setText(util.getAccountName(_account,getApplicationContext()));
						}
					};
					DialogAccountBrowser dt = new DialogAccountBrowser(ConfirmInsert.this, ifo);
					dt.show();	
				}

				dialog.dismiss();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		// onDateSet method
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			try{
				String date_selected = String.valueOf(year)+"-"+util.AddZeros(monthOfYear+1)+"-"+util.AddZeros(dayOfMonth);
				txtWhe.setText(date_selected);
				txtWhe.setText(util.dbStringDateToViewStringDate(txtWhe.getText().toString(), getApplicationContext()));
			}
			catch(Exception ex){
				util.showDialog(ex.getMessage().toString(), getApplicationContext());
			}	
		}
	};

	@Override
	protected Dialog onCreateDialog(int id) {
		Calendar c = Calendar.getInstance();
		int cyear = c.get(Calendar.YEAR);
		int cmonth = c.get(Calendar.MONTH);
		int cday = c.get(Calendar.DAY_OF_MONTH);
		DatePickerDialog dp = new DatePickerDialog(this,  mDateSetListener,  cyear, cmonth, cday);
		if (id == EDIT_DATE){
			return dp;

		}
		LayoutInflater li = LayoutInflater.from(this);
		View categoryDetailView = li.inflate(R.layout.dialog_editview, null);
		TextView tw = (TextView)categoryDetailView.findViewById(R.id.categoryEditText);
		AlertDialog.Builder categoryDetailBuilder = new AlertDialog.Builder(this);
		categoryDetailBuilder.setView(categoryDetailView);
		AlertDialog categoryDetail = categoryDetailBuilder.create();
		switch (id) {
		case EDIT_AMOUNT:
			tw.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL); //e nabijem ga ko je ovo smislio.
			categoryDetailBuilder.setTitle("Edit Amount");
			categoryDetail.setButton("OK", new OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					AlertDialog categoryDetail = (AlertDialog)dialog;
					TextView et = (TextView)categoryDetail.findViewById(R.id.categoryEditText);
					//et.setInputType(InputType.TYPE_CLASS_NUMBER);
					String amount = et.getText().toString();
					amount = Float.toString(util.getNumber("", amount));
					txtValue.setText(amount);
			 		/*
					if ("1"!=null){
						//... some code
						if (txtValue.toString().contains(",")&&((txtValue.toString().contains(".")))){
							txtValue.toString().replaceFirst(",","");
						}
						if (txtValue.toString().contains(",")&&((txtValue.toString().contains(".")))){
							txtValue.toString().replaceFirst(",","");
						}
						if (txtValue.toString().contains(",")&&((txtValue.toString().contains(".")))){
							txtValue.toString().replaceFirst(",","");
						 }

						txtValue.setText(et.getText().toString().replace(',', '.'));
					} 
					*/              
				}  
			});

			categoryDetail.setButton2("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					return;
				}}); 
			return categoryDetail;
		case EDIT_DESCRIPTION:
			categoryDetailBuilder.setTitle("Edit Description");
			categoryDetail.setButton("OK", new OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					AlertDialog categoryDetail = (AlertDialog)dialog;
					TextView et = (TextView)categoryDetail.findViewById(R.id.categoryEditText);
					if ("1"!=null){
						//... some code
						txtDescription.setText(et.getText());
					}               
				}
			});

			categoryDetail.setButton2("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					return;
				}}); 
			return categoryDetail;
		case EDIT_DATE:
			/*                categoryDetailBuilder.setTitle("Edit Date");
                categoryDetail.setButton("OK", new OnClickListener(){
	                @Override
	                public void onClick(DialogInterface dialog, int which) {
	                    AlertDialog categoryDetail = (AlertDialog)dialog;
	                    TextView et = (TextView)categoryDetail.findViewById(R.id.categoryEditText);
	                    if ("1"!=null){
	                        //... some code
	                    	txtWhe.setText(et.getText());
	                    }               
	                }
	            });
			 */
			categoryDetail.setButton2("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					return;
				}}); 
			return categoryDetail;


		default:
			break; 
		}
		return null;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case EDIT_AMOUNT:
			AlertDialog categoryDetail = (AlertDialog)dialog;
			EditText et = (EditText)categoryDetail.findViewById(R.id.categoryEditText);
			et.setText(txtValue.getText());
			break;
		case EDIT_DESCRIPTION:
			AlertDialog categoryDetail2 = (AlertDialog)dialog;
			EditText et2 = (EditText)categoryDetail2.findViewById(R.id.categoryEditText);
			String s;
			s = txtDescription.getText().toString();
			if (!s.equals("No description"))
				et2.setText(txtDescription.getText());
			break;
		case 8://EDIT_DATE://Ovaj ne sme da se podigne posto smo stavili da se javlja date picker, a ne text da kuca. uh.
			AlertDialog categoryDetail3 = (AlertDialog)dialog;
			EditText et3 = (EditText)categoryDetail3.findViewById(R.id.categoryEditText);
			et3.setText(txtWhe.getText());
			break;

		default:
			break;
		}
	}
	private class InsertTask extends AsyncTask<ContentValues, Void, Boolean> {
		private final ProgressDialog dialog = new ProgressDialog(ConfirmInsert.this);

		// can use UI thread here
		protected void onPreExecute() {
			this.dialog.setMessage("Inserting data...");
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected Boolean doInBackground(ContentValues... args) {
			try {
				util.DBInsert(args[0], getApplicationContext(), "log");
				return true;
			} catch (Exception e) {
				Log.e("CMANAGER", e.getMessage(), e);
				return false;
			}
		}

		// can use UI thread here
		protected void onPostExecute(final Boolean success) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
			if (success) {
				Toast.makeText(ConfirmInsert.this, "Insert successful!",Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(ConfirmInsert.this, "Insert failed",Toast.LENGTH_SHORT).show();
			}
		}
	}
}

